<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use neteast\Random;
use think\Validate;
use think\Db;
use app\api\controller\Quality;
use app\api\controller\Nqm;
use think\facade\Session;

/**
 * 客户相关接口
 */
class User extends Api
{

    protected $noNeedLogin = ['login'];
    // protected $noNeedRight = ['login', 'logout', 'menu'];

    public function initialize()
    {
        parent::initialize();
    }
    /**
     * 获取客户所有应用
     */
    public function apps(){
       $userinfo = $this->auth->getUserinfo();
        $id = $userinfo['id'];
        $dpi = Db::name('user_config')->where('user_id',$id)->value('dpi');
        $dpi_arr = json_decode($dpi,true);
        $data = $dpi_arr['apps'];
        $this->success('', $data); 
    }
    /**
     * 获取客户信息
     */
    public function info(){
        $userinfo = $this->auth->getUserinfo();
        $id = $userinfo['id'];
        $data = Db::name('user_info')
            ->alias('info')
            ->join('user', 'info.user_id=user.id')
            ->join('user_meal meal',"meal.id=info.user_meal_id","left")
            ->field('info.*, user.nickname, user.prevtime,meal.meal_name')
            ->where('user_id',$id)->find();
        $user_config = DB::name('user_config')->where(['user_id'=>$id])->find();
        unset($data['id']);
        unset($data['user_id']);
        unset($data['createtime']);
        unset($data['updatetime']);
        if(!$data['expired']){
            $data['expired'] = '待定';
        }
        //增加客服电话、dns地址
        $data['dpi'] = json_decode($user_config['dpi']);
        $data['probe'] = json_decode($user_config['probe']);
        $this->success('', $data);
    }
    /**
     * 获取客户app业务测试配置信息
     */
    public function business(){
        $userinfo = $this->auth->getUserinfo();
        $id = $userinfo['id'];
        $data = Db::name('user_app_business')->where('user_id',$id)->find();
        if(!$data){
            $this->error(__('Please config app business'));
        }
        if(!$data['velocity']){
            $this->error(__('Please config app business velocity'));
        }
        if(!$data['diagnosis']){
            $this->error(__('Please config app business diagnosis'));
        }
        $data['velocity'] = json_decode($data['velocity'],true); //格式化一下
        $data['diagnosis'] = json_decode($data['diagnosis'],true); //格式化一下
        $other = json_decode($data['other'], true);
        unset($data['other']);
        $data = array_merge($other, $data);
        unset($data['id']);
        unset($data['user_id']);
        unset($data['createtime']);
        unset($data['updatetime']);
        $this->success('', $data);
    }

    /**
     * 获取客户app所需所有配置信息
     */
    public function app_config(){
        $userinfo = $this->auth->getUserinfo();
        $id = $userinfo['id'];
        $data = Db::name('user_app_business')->where('user_id',$id)->find();
        if(!$data){
            $this->error(__('Please config app business'));
        }
        if(!$data['velocity']){
            $this->error(__('Please config app business velocity'));
        }
        if(!$data['diagnosis']){
            $this->error(__('Please config app business diagnosis'));
        }
        $data['velocity'] = json_decode($data['velocity'],true); //格式化一下
        $data['diagnosis'] = json_decode($data['diagnosis'],true); //格式化一下
        $other = json_decode($data['other'], true);
        unset($data['other']);
        $data = array_merge($other, $data);
        unset($data['id']);
        unset($data['user_id']);
        unset($data['createtime']);
        unset($data['updatetime']);
        $info = Db::name('user_info')
            ->alias('info')
            ->join('user', 'info.user_id=user.id')
            ->field('info.*, user.nickname, user.prevtime')
            ->where('user_id',$id)->find();
        if(!$info['expired']){
            $day_config = config('day_expired');
            $info['expired'] = date("Y-m-d",strtotime("+{$day_config} day",time()));
        }
        $data['expired'] = $info['expired'];
        $data['userBandwidth']['size'] = floatval(conversion_unit_text(conversion_unit($info['bandwidth']), 'M'));
        $data['userBandwidth']['unit'] = 'Mbps';        
        $this->success('', $data);
    }

    //首页四个指标值
    public function snap(){
        $userinfo = $this->auth->getUserinfo();
        $id = $userinfo['id'];
        $user_obj = \app\common\model\User::get($id);
        $data = Db::name('user_info')->field('bandwidth')->where('user_id',$id)->find();
        $data['bandwidth'] = isset($data['bandwidth']) ? $data['bandwidth'] : '';
        $data['bandwidth_fix'] = conversion_unit($data['bandwidth']);
        $data['bandwidth'] = floatval(conversion_unit_text($data['bandwidth_fix'], 'M')).'Mbps';
        
        //如果用户不是小微客户，展示这两项
        // if($user_obj->group['name'] != '小微企业版'){
            $data['breakdown'] = count($this->breakdown('arr'));
            $data['breakdown_quality'] = $this->get_level('故障日志', $data['breakdown']);
        // }
        // $obj = new Quality;
        if($user_obj->group['name'] != '小微企业版'){  
            $obj = new Nqm; //对接新版nqm
            $data['quality'] = $obj->quality(); //综合质量分
            $data['link_quality'] = $obj->type_quality('basedlink'); //链路质量分
            $row = $obj->link('app'); //应用质量分
            $data['app_quality'] = $row['score'];
            $data['appqualitys'] = $row['appqualitys'];
        }
        $this->success('', $data);
    }

    /**
     * 获取客户的故障日志，不传日期，默认当天的
     */
    public function breakdown($return='json'){
        $userinfo = $this->auth->getUserinfo();
        $id = $userinfo['id'];
        $starttime = $this->request->post('starttime');
        if(!$starttime){
            $starttime = date('Ymd000000');
        }else{
            $starttime = date('YmdHis', strtotime($starttime));
        }
        $endtime = $this->request->post('endtime');
        if(strlen($endtime) == 10){
            $endtime .= '23:59:59'; 
        }
        if(!$endtime){
            $endtime = date('YmdHis');
        }else{
            $endtime = date('YmdHis', strtotime($endtime));
        }
        $rs = Db::name('user_task')->where('user_id',$id)->select();
        if(!$rs){
            $this->error(__('Please config breakdown'));
        }
        $data = Db::name('user_task')
            ->alias('t')
            ->field('e.reporttime,e.content')
            ->join('t_user_task_error e', 't.id=e.user_task_id','right')
            ->where('user_id',$id)
            ->where('e.reporttime >= "'.$starttime .'" and e.reporttime <="'.$endtime.'"' )
            ->select();
        // echo (Db::name('user_task')->getLastSql());exit;
        if($return == 'arr'){
            return $data;
        }else{
            //格式化时间
            foreach ($data as $key => $value) {
                $data[$key]['reporttime'] = Date('Y-m-d H:i:s',strtotime($value['reporttime']));
            }
            $this->success('', $data);
        }
    }
    /**
     * 获取用户菜单
     */
    public function menu(){
        //判断来源，app和web显示不同的菜单
        $terminal = $this->request->post('terminal');
        $rules = $this->auth->getRuleList();
        
        foreach ($rules as $key => $value) {
            if($value['ismenu'] == 0){
                unset($rules[$key]);
            }
            //区分终端
            $name_arr = explode('/', $value['name']);
            if($terminal == 'web'){
                if($name_arr[0] != 'index'){
                    unset($rules[$key]);
                }
            }else if($terminal == 'app'){
                if($name_arr[0] != 'app'){
                    unset($rules[$key]);
                }
            }
        }
        
        // dump($rules);exit;
        $data = array();
        foreach ($rules as $key => $value) {
            unset($value['id']);
            unset($value['pid']);
            unset($value['ismenu']);
            unset($value['weigh']);
            $data[] = $value;
        }
        
        $this->success('', $data);
    }

    /**
     * 获取用户权限
     */
    public function rule(){
        $terminal = $this->request->post('terminal');
        $rules = $this->auth->getRuleList();
        foreach ($rules as $key => $value) {
            //区分终端
            $name_arr = explode('/', $value['name']);
            if($terminal == 'web'){
                if($name_arr[0] != 'index' && $name_arr[0] != 'api'){
                    unset($rules[$key]);
                }
            }else if($terminal == 'app'){
                if($name_arr[0] != 'app'){
                    unset($rules[$key]);
                }
            }
        }
        $data = array();
        foreach ($rules as $key => $value) {
            unset($value['id']);
            unset($value['pid']);
            unset($value['ismenu']);
            unset($value['weigh']);
            $data[] = $value;
        }
        $this->success('', $data);
    }


    /**
     * 会员登录
     * 
     * @param string $account 账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password)
        {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret)
        {
            $userinfo = $this->auth->getUserinfo();
            // dump($userinfo);exit;
            unset($userinfo['user_id']);
            unset($userinfo['createtime']);
            unset($userinfo['expires_in']);
            unset($userinfo['id']);
            // $data = ['userinfo' => $userinfo];
            $data = $userinfo;
            $this->success(__('Logged in successful'), $data);
        }
        else
        {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注销登录
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success(__('Logout successful'), "");
    }

    // 修改密码
    public function userupdate(){
        if ($this->request->isPost()) {
            $this->model = new \app\admin\model\User;
            $userinfo = $this->auth->getUserinfo();
            $row = $this->model->get($userinfo['id']);
            $params = $this->request->post();
            $old_password = $this->request->post('old_password');
            $nickname = $this->request->post('nickname');
            $password = $this->request->post('password');
            if(!$nickname){
                if(!$old_password){
                    $this->error('old_password参数不存在');
                }
                if(md5($old_password . $row['salt']) != $row['password']){
                    $this->error("旧密码输入错误,请重新输入");
                }
            }
            if ($params) {
                try {
                    $params['id'] = $userinfo['id'];
                    $validate = new \app\admin\validate\User;
                    if(!$validate->scene('edit')->check($params)){
                        $this->error($validate->getError());
                    }
                    if(empty($params['password'])){
                        $params['password'] = "";
                    }
                    if(!$nickname){
                        if(!$password){
                            $this->error("请输入新密码");
                        }
                    }
                    $result = $row->allowField(true)->force()->save($params);
                    if ($result !== false) {
                        $this->success("修改成功");
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
    }
}
